//
//  CK_MenuViewController.m
//  MenuDemo
//
//  Created by 陈凯 on 16/4/14.
//  Copyright © 2016年 鸥！陈凯. All rights reserved.
//

#import "CK_MenuViewController.h"
#import "JaneLoginViewController.h"
// 抽屉展开的程度
#define kMenuLeftWidth [UIScreen mainScreen].bounds.size.width * 0.7

@interface CK_MenuViewController ()<UITableViewDataSource, UITableViewDelegate>

// 默认左侧tableView
@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic,assign) NSInteger index;
@end

@implementation CK_MenuViewController
// 判断当前是否展开
- (BOOL)isShowing {
    if (self.centerViewController.view.transform.tx > 0) {
        return YES;
    }
    return NO;
}
// 初始化方法
static CK_MenuViewController *CK_menuVC = nil;
+ (instancetype)instanceWithLeftViewController:(UIViewController *)leftVC CenterViewController:(UIViewController *)centerVC {
    @synchronized(self) {
        if (!CK_menuVC) {
            
            CK_menuVC = [[CK_MenuViewController alloc]init];
            // 设置window的rootViewController
            [UIApplication sharedApplication].keyWindow.rootViewController = CK_menuVC;
            // 设置属性
            CK_menuVC.leftViewController = leftVC;
            CK_menuVC.centerViewController = centerVC;
            // 添加子视图控制器和子视图
            if (leftVC) {
                [CK_menuVC addChildViewController:leftVC];
                [CK_menuVC.view addSubview:leftVC.view];
            }else {
                [CK_menuVC setupLeftViewController];
            }
            if (centerVC) {
                [CK_menuVC addChildViewController:centerVC];
                [CK_menuVC.view addSubview:centerVC.view];
            }
        }
    }
    return CK_menuVC;
}
// 默认的菜单视图
- (void)setupLeftViewController {
    self.leftTableView = [[UITableView alloc]    initWithFrame:CGRectMake(-kMenuLeftWidth, 0, kMenuLeftWidth, self.view.frame.size.height) style:UITableViewStylePlain];
    // 设置数据源
    self.leftTableView.dataSource = self;
    // 代理
    self.leftTableView.delegate = self;
    self.leftTableView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.leftTableView];
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark - UITableViewDataSource
// 数据源代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.menuArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuserID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserID];
    }
    cell.textLabel.text = self.menuArray[indexPath.row];
    if (indexPath.row == self.index) {
        cell.textLabel.textColor = [UIColor whiteColor];
    }else{
        cell.textLabel.textColor = [UIColor grayColor];

    }
    
    cell.backgroundColor = [UIColor blackColor];
    
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kMenuLeftWidth, 200)];
//    UIImageView *titleImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20, kMenuLeftWidth, 65)];
//    titleImgView.image = [UIImage imageNamed:@"header.png"];
//    [headView addSubview:titleImgView];

    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 10, 64, 64);
    [searchBtn setImage:[UIImage imageNamed:@"搜索.jpg"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:searchBtn];
    
    UIButton *downloadsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    downloadsBtn.frame = CGRectMake(70, 10, 64, 64);
    [downloadsBtn setImage:[UIImage imageNamed:@"下载.jpg"] forState:UIControlStateNormal];
    [downloadsBtn addTarget:self action:@selector(downloadsBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:downloadsBtn];
    
    UIButton *likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    likeBtn.frame = CGRectMake(140, 10, 64, 64);
    [likeBtn setImage:[UIImage imageNamed:@"喜爱.jpg"] forState:UIControlStateNormal];
    [likeBtn addTarget:self action:@selector(likeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:likeBtn];
    
    UIButton *messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    messageBtn.frame = CGRectMake(210, 10, 64, 64);
    [messageBtn setImage:[UIImage imageNamed:@"消息.jpg"] forState:UIControlStateNormal];
    [messageBtn addTarget:self action:@selector(messageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:messageBtn];
//    
//    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(120, 80, 100, 100)];
//    label.text = @"未登录";
//    label.font = [UIFont systemFontOfSize:20];
//    label.textColor = [UIColor whiteColor];
//    [headView addSubview:label];
    
    
    UIButton *headerImgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    headerImgBtn.frame = CGRectMake(80, 90, 80, 80);
    [headerImgBtn setImage:[UIImage imageNamed:@"头像.png"] forState:UIControlStateNormal];
    [headerImgBtn addTarget:self action:@selector(headerImgBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:headerImgBtn];
    return headView;
    }
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 200;
}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0,500, kMenuLeftWidth,100)];
//    UIButton *footerImgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    footerImgBtn.frame = CGRectMake(30, 210, 50, 50);
//    [footerImgBtn setImage:[UIImage imageNamed:@"头像.png"] forState:UIControlStateNormal];
//    [footerImgBtn addTarget:self action:@selector(headerImgBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    [footerView addSubview:footerImgBtn];
//    
//    UILabel *footerLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 190, 100, 80)];
//    footerLabel.text = @"歌曲名";
//    footerLabel.textColor = [UIColor whiteColor];
//    footerLabel.font = [UIFont systemFontOfSize:18];
//    [footerView addSubview:footerLabel];
//    
//    return footerView;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return 100;
//    
//}
- (void)searchBtnAction:(UIButton *)search {
    [[CK_MenuViewController getMenuViewController]hideLeftViewController];
}
- (void)downloadsBtnAction:(UIButton *)downloads {
    [[CK_MenuViewController getMenuViewController]hideLeftViewController];
}
- (void)likeBtnAction:(UIButton *)like {
    [[CK_MenuViewController getMenuViewController]hideLeftViewController];
}
- (void)messageBtnAction:(UIButton *)message {
    [[CK_MenuViewController getMenuViewController]hideLeftViewController];
}
- (void)headerImgBtnAction:(UIButton *)headerImg {
    JaneLoginViewController *loginVC = [[JaneLoginViewController alloc]init];
        [self presentViewController:loginVC animated:YES completion:nil];
   
}
// menuArray的setter方法
- (void)setMenuArray:(NSMutableArray *)menuArray {
    if (_menuArray != menuArray) {
        _menuArray  = nil;
        _menuArray  = menuArray;
        [self.leftTableView reloadData];
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.index = indexPath.row;
    [tableView reloadData];
    // 代理 传值
    if ([self.menuDelegate respondsToSelector:@selector(didClickMenuIndex:Title:)]) {
        [self.menuDelegate didClickMenuIndex:indexPath.row Title:self.menuArray[indexPath.row]];
    }
    // 关闭抽屉
    [self hideLeftViewController];
}

// 获取抽屉方法
+ (instancetype)getMenuViewController {
    return CK_menuVC;
}

// 展示左侧菜单
- (void)showLeftViewController {
    // 动画展开
    [self showLeftViewController:0.7];
    
}
- (void)showLeftViewController:(CGFloat)duration{
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
    }];

}
// 关闭左侧菜单
- (void)hideLeftViewController {
    [self hideLeftViewController:0.7];
}
- (void)hideLeftViewController:(CGFloat)duration {
    // 动画关闭
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panMenuWithPanGesture:)];
    [self.view addGestureRecognizer:pan];
    // Do any additional setup after loading the view.
}


// 静态变量保存初始状态
static CGPoint begin;
static CGAffineTransform transform;
- (void)panMenuWithPanGesture:(UIPanGestureRecognizer *)pan {
    // 位移量
    CGPoint translatePoint = CGPointZero;
    // 开始手势时的位置
    if (pan.state == UIGestureRecognizerStateBegan) {
        begin = [pan locationInView:self.view];
        transform = self.centerViewController.view.transform;
    }
    // 手势过程中的位置
    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint end = [pan locationInView:self.view];
        translatePoint = CGPointMake(end.x - begin.x, 0);
    }
    // 手势结束时的位置
    if (pan.state == UIGestureRecognizerStateCancelled || pan.state == UIGestureRecognizerStateEnded) {
        if ([pan velocityInView:self.view].x > 0) {
            // 动画设置动画时长
            [self showLeftViewController:0.13];
        }else {
            [self hideLeftViewController:0.13];
        }
        return;
    }
    // 手势过程中，对视图进行位移
    if(self.centerViewController.view.transform.tx >= 0 && self.centerViewController.view.transform.tx <= kMenuLeftWidth) {
        self.centerViewController.view.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
        self.leftViewController.view.transform = CGAffineTransformTranslate(transform,translatePoint.x, 0);
        self.leftTableView.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
